package com.guodi.common.utils;

import org.apache.commons.compress.utils.IOUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.net.ssl.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.Socket;
import java.net.URL;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @描述：HTTP请求对象
 * @作者：彭辉
 * @时间：2019/1/13 12:05
 */
public class HttpRequester {

    private static Pattern regex = Pattern.compile("[\u4e00-\u9fa5]");

    public static String encode(String str) {
        Matcher m = regex.matcher(str);
        StringBuffer b = new StringBuffer();
        try {
            while (m.find()) {
                String key = m.group();
                m.appendReplacement(b, URLEncoder.encode(key, "UTF-8"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        m.appendTail(b);
        return b.toString();
    }

    /**
     * @描述：发送GET请求
     * @入参：url地址
     * @作者：彭辉
     * @时间：2019/1/13 12:06
     */
    public <T> T sendGet(String url) throws IOException {
        return this.send2(RepalceDXYUrlUtil.repalceDXYUrl(url), "GET", null, null);
    }

    /**
     * @描述：发送GET请求
     * @入参：URL：url地址，params：参数集合
     * @作者：彭辉
     * @时间：2019/1/13 12:06
     */
    public <T> T sendGet(String url, Map<String, String> params)
            throws IOException {
        return this.send2(RepalceDXYUrlUtil.repalceDXYUrl(url), "GET", params, null);
    }

    /**
     * @描述：发送GET请求
     * @入参：URL：url地址，params：参数集合，propertys：属性集合
     * @作者：彭辉
     * @时间：2019/1/13 12:06
     */
    public <T> T sendGet(String url, Map<String, String> params,
                         Map<String, String> propertys) throws IOException {
        return this.send(url, "GET", params, propertys, null);
    }

    /**
     * @描述：发送POST请求
     * @入参：url地址
     * @作者：彭辉
     * @时间：2019/1/13 12:06
     */
    public <T> T sendPost(String url) throws IOException {
        return this.send(RepalceDXYUrlUtil.repalceDXYUrl(url), "POST", null, null, null);
    }

    /**
     * @描述：发送POST请求
     * @入参：URL：url地址，params：参数集合
     * @作者：彭辉
     * @时间：2019/1/13 12:06
     */
    public <T> T sendPost(String url, Map<String, String> params)
            throws IOException {
        String newUrl = RepalceDXYUrlUtil.repalceDXYUrl(url);
        return this.send(newUrl, "POST", params, null, null);
    }

    public <T> T   sendPost2(String url,Map<String,String> params) throws IOException {
        String newUrl = RepalceDXYUrlUtil.repalceDXYUrl(url);
        return send2(newUrl,"POST",params,null);
    }

    /**
     * @描述：发送POST请求
     * @入参：URL：url地址，params：参数集合，propertys：属性集合
     * @作者：彭辉
     * @时间：2019/1/13 12:06
     */
    public <T> T sendPost(String url, Map<String, String> params,
                          Map<String, String> propertys) throws IOException {
        return this.send(url, "POST", params, propertys, null);
    }

    /**
     * @描述：发送POST请求
     * @入参：URL：url地址，params：参数集合
     * @作者：彭辉
     * @时间：2019/1/13 12:06
     */
    public <T> T sendPost(String url, Map<String, String> params, Integer readTimeout)
            throws IOException {
        return this.send(url, "POST", params, null,readTimeout);
    }

    /**
     * @描述：发送HTTP请求
     * @入参：URL：url地址，method：请求方式，parameters：参数集合，propertys：属性集合
     * @作者：彭辉
     * @时间：2019/1/13 12:10
     */
    private synchronized <T> T send(String url, String method,
                                    Map<String, String> parameters, Map<String, String> propertys, Integer readTimeout)
            throws IOException {
        HttpURLConnection urlConnection = null;
        StringBuffer param = new StringBuffer();
        try {
            //将最后的?去掉
            url = url.replaceAll("\\?$", "");
            if (method.equalsIgnoreCase("GET") && parameters != null) {
                int i = 0;
                for (String key : parameters.keySet()) {
                    if (i == 0 && !url.contains("?")) {
                        param.append("?");
                    } else {
                        param.append("&");
                    }
                    String value = String.valueOf(parameters.get(key));
                    //if (!Common.isCheckNull(value)) {
                    if (value == null) {
                        param.append(URLEncoder.encode(key, "UTF-8")).append("=").append(URLEncoder.encode(value, "UTF-8"));
                    } else {
                        param.append(URLEncoder.encode(key, "UTF-8")).append("=");
                    }
                    i++;
                }
                url += param;
            }
            if (method.equalsIgnoreCase("POST") && parameters != null) {
                int i = 0;
                for (String key : parameters.keySet()) {
                    if (i != 0) param.append("&");
                    String value = String.valueOf(parameters.get(key));
                    if (StringUtils.isEmpty(value)) {
                        param.append(URLEncoder.encode(key, "UTF-8")).append("=");
                    } else {
                        param.append(URLEncoder.encode(key, "UTF-8")).append("=").append(URLEncoder.encode(value, "UTF-8"));
                    }
                    i++;
                }
            }
            //将中文转码
            url = encode(url);
            URL httpUrl = new URL(url);
            urlConnection = (HttpURLConnection) httpUrl.openConnection();
            if (method.equalsIgnoreCase("GET")) {
                urlConnection.setRequestMethod("GET");// 提交模式
            } else {
                urlConnection.setRequestMethod("POST");// 提交模式
            }
            urlConnection.setRequestMethod(method);
            urlConnection.setDoOutput(true);
            urlConnection.setDoInput(true);
            urlConnection.setUseCaches(false);
//            urlConnection.addRequestProperty("Content-Length",""+encode(param.toString()).getBytes().length);
            // 设置获取连接超时时间
            //urlConnection.setConnectTimeout(10000);
            // 设置读取返回数据超时时间
            if (Objects.isNull(readTimeout)){
                // 默认30秒
                urlConnection.setReadTimeout(1000 * 30);
            }else{
                urlConnection.setReadTimeout(readTimeout);
            }
            if (propertys != null) {
                for (String key : propertys.keySet()) {
                    urlConnection.addRequestProperty(key, propertys.get(key));
                }
            }
            if (method.equalsIgnoreCase("POST") && parameters != null) {
                OutputStream opt = urlConnection.getOutputStream();
                opt.write(encode(param.toString()).getBytes());
                opt.flush();
                opt.close();
            }

            HttpRespons httpResponser = getHttpRespons();
            String ecod = "UTF-8";
            InputStream input = urlConnection.getInputStream();
            byte[] bytay = getByteArr(input);
            //判断是否为文本
            boolean isText = true;
            for (int i = 0; i < bytay.length; i++) {
                if (bytay[i] == 0) {
                    isText = false;
                    break;
                }
            }
            httpResponser.isText = isText;    //判断是否文本格式
            httpResponser.bytay = bytay;    //字节数组
            httpResponser.urlString = url;
            httpResponser.defaultPort = urlConnection.getURL().getDefaultPort();
            httpResponser.file = urlConnection.getURL().getFile();
            httpResponser.host = urlConnection.getURL().getHost();
            httpResponser.path = urlConnection.getURL().getPath();
            httpResponser.port = urlConnection.getURL().getPort();
            httpResponser.protocol = urlConnection.getURL().getProtocol();
            httpResponser.query = urlConnection.getURL().getQuery();
            httpResponser.ref = urlConnection.getURL().getRef();
            httpResponser.userInfo = urlConnection.getURL().getUserInfo();

            //httpResponser.content = content;
            httpResponser.contentEncoding = ecod;
            httpResponser.code = urlConnection.getResponseCode();
            httpResponser.message = urlConnection.getResponseMessage();
            httpResponser.contentType = urlConnection.getContentType();
            httpResponser.method = urlConnection.getRequestMethod();
            httpResponser.connectTimeout = urlConnection.getConnectTimeout();
            httpResponser.readTimeout = urlConnection.getReadTimeout();
            return (T) httpResponser;
        } catch (IOException e) {
            if (urlConnection != null) {
                System.out.println("url: " + urlConnection.getURL());
            }
            throw e;
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
        }
    }

    /**
     * 发送请求，返回流
     * @入参： url 请求地址
     * @入参： method 请求方法，get或者post
     * @入参： parameters 参数
     * @入参： readTimeout 超时时间，毫秒单位，默认30秒
     * @return
     * @throws IOException
     */
    public synchronized void sendReturnStream(String url, String method, Map<String, String> parameters, Integer readTimeout, OutputStream outputStream) throws IOException {
        HttpURLConnection urlConnection = null;
        StringBuffer param = new StringBuffer();
        try {
            //将最后的?去掉
            url = url.replaceAll("\\?$", "");
            if (method.equalsIgnoreCase("GET") && parameters != null) {
                int i = 0;
                for (String key : parameters.keySet()) {
                    if (i == 0 && !url.contains("?")) {
                        param.append("?");
                    } else {
                        param.append("&");
                    }
                    String value = String.valueOf(parameters.get(key));
                    //if (!Common.isCheckNull(value)) {
                    if (value != null) {
                        param.append(URLEncoder.encode(key, "UTF-8")).append("=").append(URLEncoder.encode(value, "UTF-8"));
                    } else {
                        param.append(URLEncoder.encode(key, "UTF-8")).append("=");
                    }
                    i++;
                }
                url += param;
            }
            if (method.equalsIgnoreCase("POST") && parameters != null) {
                int i = 0;
                for (String key : parameters.keySet()) {
                    if (i != 0) param.append("&");
                    String value = String.valueOf(parameters.get(key));
                    if (StringUtils.isEmpty(value)) {
                        param.append(URLEncoder.encode(key, "UTF-8")).append("=");
                    } else {
                        param.append(URLEncoder.encode(key, "UTF-8")).append("=").append(URLEncoder.encode(value, "UTF-8"));
                    }
                    i++;
                }
            }
            //将中文转码
            url = encode(url);
            URL httpUrl = new URL(url);
            urlConnection = (HttpURLConnection) httpUrl.openConnection();
            if (method.equalsIgnoreCase("GET")) {
                urlConnection.setRequestMethod("GET");// 提交模式
            } else {
                urlConnection.setRequestMethod("POST");// 提交模式
            }
            urlConnection.setRequestMethod(method);
            urlConnection.setDoOutput(true);
            urlConnection.setDoInput(true);
            urlConnection.setUseCaches(false);
            // 设置获取连接超时时间，3秒超时
            urlConnection.setConnectTimeout(1000 * 3);
            // 设置读取返回数据超时时间
            if (Objects.isNull(readTimeout)){
                // 默认30秒
                urlConnection.setReadTimeout(1000 * 30);
            }else{
                urlConnection.setReadTimeout(readTimeout);
            }

            if (method.equalsIgnoreCase("POST") && parameters != null) {
                OutputStream opt = urlConnection.getOutputStream();
                opt.write(encode(param.toString()).getBytes());
                opt.flush();
                opt.close();
            }
            InputStream input = urlConnection.getInputStream();
            IOUtils.copy(input, outputStream);
        } catch (IOException e) {
            if (urlConnection != null) {
                System.out.println("url: " + urlConnection.getURL());
            }
            throw e;
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
        }
    }




    public HttpRespons getHttpRespons() {
        return new HttpRespons();
    }

    private byte[] getByteArr(InputStream input) throws IOException {
        List<byte[]> list = new ArrayList<byte[]>();
        int total = 0;
        while (true) {
            int size = 64;
            byte[] buf = new byte[size];
            int ind = input.read(buf);
            if (ind == -1) break;
            if (ind < size) {
                byte[] bufnew = new byte[ind];
                System.arraycopy(buf, 0, bufnew, 0, ind);
                list.add(bufnew);
            } else {
                list.add(buf);
            }
            total += ind;
        }
        input.close();
        byte[] bytay = new byte[total];
        for (int i = 0, n = 0; i < list.size(); i++) {
            byte[] byt = list.get(i);
            for (int j = 0; j < byt.length; j++, n++) {
                byte temp = byt[j];
                bytay[n] = temp;
            }
        }
        return bytay;
    }



    /**
     * 从url中解析参数并返回原始url
     * @入参： url
     * @入参： paramsMap 参数map，用于存放参数
     * @出参： 返回不带参数的完整地址
     */
    public static String getParamFromUrl(String url,Map<String,String> paramsMap){
        if (!org.apache.commons.lang3.StringUtils.isNotBlank(url)){
            throw new RuntimeException("服务地址为空");
        }
        if (url.indexOf("?") == -1){
            return url;
        }
        // 获取原始url
        String originalUrl = url.substring(0, url.indexOf("?"));
        // 解析参数
        String paramsStr = url.substring(url.indexOf("?") + 1);
        if (org.apache.commons.lang3.StringUtils.isNotBlank(paramsStr) && paramsMap != null){
            String[] paramsArray;
            // &的html转义
            if(paramsStr.contains("&amp;")){
                paramsArray = paramsStr.split("&amp;");
            }else{
                paramsArray = paramsStr.split("&");
            }
            if(paramsArray != null && paramsArray.length > 0){
                for(String params : paramsArray) {
                    String[] split = params.split("=");
                    paramsMap.put(split[0],split[1]);
                }
            }
        }
        return originalUrl;
    }

    /**
     * 给url追加参数
     * @入参： url 原始url
     * @入参： paramsMap 参数
     * @出参： 追加参数后的url
     */
    public static String setParamToUrl(String url,Map<String,String> paramsMap){
        // 给代理url拼接数据源的参数
        if (paramsMap != null && !paramsMap.isEmpty()){
            if (url.indexOf("?") == -1) {
                url = url + "?";
            }else{
                if (!url.endsWith("?")){
                    url = url + "&";
                }
            }
            for(Map.Entry<String, String> stringStringEntry : paramsMap.entrySet()) {
                url += stringStringEntry.getKey() + "=" + stringStringEntry.getValue() + "&";
            }
            url = url.endsWith("&")? url.substring(0,url.length() - 1): url;
        }
        return url;
    }


    /**
     * @描述：发送带文件的post请求，注意：这个方法是以 multipart/form-data 形式来发送post请求的
     * @入参：urlStr url地址
     * @入参：paramsMap 键值对参数，key为对应的参数名
     * @入参：filesMap 文件参数，key为对应的参数名
     * @入参：outputStream 输出流，如果为null，则将返回内容转成字符串返回
     * @作者：陈宏成
     * @时间：2021-04-29 21:22:00
     */
    public static String sendPostFile(String urlStr, Map<String ,String > paramsMap, Map<String, MultipartFile> filesMap,OutputStream outputStream){
        String res = "";
        HttpURLConnection conn = null;
        String BOUNDARY = "---------------------------123821742118716"; //boundary就是request头和上传文件内容的分隔符
        try {
            URL url = new URL(urlStr);
            conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(30000);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
            conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);

            OutputStream out = new DataOutputStream(conn.getOutputStream());
            // text
            if (paramsMap != null) {
                StringBuffer strBuf = new StringBuffer();
                Iterator<Map.Entry<String, String>> iter = paramsMap.entrySet().iterator();
                while (iter.hasNext()) {
                    Map.Entry<String, String> entry = iter.next();
                    String inputName = (String) entry.getKey();
                    String inputValue = (String) entry.getValue();
                    if (inputValue == null) {
                        continue;
                    }
                    strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
                    strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"\r\n\r\n");
                    strBuf.append(inputValue);
                }
                out.write(strBuf.toString().getBytes());
            }

            // file
            if (filesMap != null) {
                Iterator<Map.Entry<String, MultipartFile>> iter = filesMap.entrySet().iterator();
                while (iter.hasNext()) {
                    Map.Entry<String, MultipartFile> entry = iter.next();
                    String inputName = entry.getKey();
                    MultipartFile multipartFile = entry.getValue();
                    if (multipartFile == null) {
                        continue;
                    }
                    String contentType = multipartFile.getContentType();

                    StringBuffer strBuf = new StringBuffer();
                    strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
                    strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"; filename=\"" + multipartFile.getOriginalFilename() + "\"\r\n");
                    strBuf.append("Content-Type:" + contentType + "\r\n\r\n");

                    out.write(strBuf.toString().getBytes());

                    DataInputStream in = new DataInputStream(multipartFile.getInputStream());
                    int bytes = 0;
                    byte[] bufferOut = new byte[1024];
                    while ((bytes = in.read(bufferOut)) != -1) {
                        out.write(bufferOut, 0, bytes);
                    }
                    in.close();
                }
            }

            byte[] endData = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
            out.write(endData);
            out.flush();
            out.close();

            if (outputStream == null){
                // 读取返回数据
                StringBuffer strBuf = new StringBuffer();
                BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                String line = null;
                while ((line = reader.readLine()) != null) {
                    strBuf.append(line).append("\n");
                }
                res = strBuf.toString();
                reader.close();
                reader = null;
            }else{
                InputStream inputStream = conn.getInputStream();
                byte[] bytes = new byte[1024];
                int len = 0;
                while ((len = inputStream.read(bytes)) != -1){
                    outputStream.write(bytes,0,len);
                }
                inputStream.close();
                outputStream.flush();
                outputStream.close();
            }


        } catch (Exception e) {
            System.out.println("发送POST请求出错。" + urlStr);
            e.printStackTrace();
        } finally {
            if (conn != null) {
                conn.disconnect();
                conn = null;
            }
        }
        return res;
    }



    private HttpURLConnection  getHttpURLConnection(URL url) throws IOException {
//        URL url = new URL(uri);
        String protocol = url.getProtocol();
        HttpURLConnection httpConn =  null;
        if("https".equals(protocol)){
            SSLContext ctx = null;
            try {
                ctx = SSLContext.getInstance("TLS");
                ctx.init(new KeyManager[0], new TrustManager[] { new MyTrustManager() }, new SecureRandom());
            } catch (KeyManagementException e) {
                e.printStackTrace();
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
            SSLSocketFactory ssf = ctx.getSocketFactory();
            HttpsURLConnection httpsConn = (HttpsURLConnection) url.openConnection();
            httpsConn.setSSLSocketFactory(ssf);
            httpsConn.setHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String arg0, SSLSession arg1) {
                    return true;
                }
            });
            httpConn = httpsConn;

        }else{
            httpConn = (HttpURLConnection) url.openConnection();
        }
        return httpConn;
    }

    private static final class DefaultTrustManager implements X509TrustManager {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    }

    private static final class MyTrustManager extends X509ExtendedTrustManager {
        @Override
        public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

        }

        @Override
        public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        @Override
        public void checkClientTrusted(X509Certificate[] x509Certificates, String s, Socket socket) throws CertificateException {

        }

        @Override
        public void checkServerTrusted(X509Certificate[] x509Certificates, String s, Socket socket) throws CertificateException {

        }

        @Override
        public void checkClientTrusted(X509Certificate[] x509Certificates, String s, SSLEngine sslEngine) throws CertificateException {

        }

        @Override
        public void checkServerTrusted(X509Certificate[] x509Certificates, String s, SSLEngine sslEngine) throws CertificateException {

        }
    }


    private synchronized <T> T send2(String url, String method,
                                    Map<String, String> parameters, Map<String, String> propertys) throws IOException {
        HttpURLConnection urlConnection = null;
        StringBuffer param = new StringBuffer();
        try {
            //将最后的?去掉
            url = url.replaceAll("\\?$", "");
            if (method.equalsIgnoreCase("GET") && parameters != null) {
                int i = 0;
                for (String key : parameters.keySet()) {
                    if (i == 0 && !url.contains("?")) {
                        param.append("?");
                    } else {
                        param.append("&");
                    }
                    String value = String.valueOf(parameters.get(key));
                    //if (!Common.isCheckNull(value)) {
                    if (value == null) {
                        param.append(URLEncoder.encode(key, "UTF-8")).append("=").append(URLEncoder.encode(value, "UTF-8"));
                    } else {
                        param.append(URLEncoder.encode(key, "UTF-8")).append("=");
                    }
                    i++;
                }
                url += param;
            }
            if (method.equalsIgnoreCase("POST") && parameters != null) {
                int i = 0;
                for (String key : parameters.keySet()) {
                    if (i != 0) param.append("&");
                    String value = String.valueOf(parameters.get(key));
                    if (StringUtils.isEmpty(value)) {
                        param.append(URLEncoder.encode(key, "UTF-8")).append("=");
                    } else {
                        param.append(URLEncoder.encode(key, "UTF-8")).append("=").append(URLEncoder.encode(value, "UTF-8"));
                    }
                    i++;
                }
            }
            //将中文转码
            url = encode(url);
            URL httpUrl = new URL(url);
            urlConnection = (HttpURLConnection) getHttpURLConnection(httpUrl);
            if (method.equalsIgnoreCase("GET")) {
                urlConnection.setRequestMethod("GET");// 提交模式
            } else {
                urlConnection.setRequestMethod("POST");// 提交模式
            }
            urlConnection.setRequestMethod(method);
            urlConnection.setDoOutput(true);
            urlConnection.setDoInput(true);
            urlConnection.setUseCaches(false);
//            urlConnection.addRequestProperty("Content-Length",""+encode(param.toString()).getBytes().length);
            // 设置获取连接超时时间
            //urlConnection.setConnectTimeout(10000);
            // 设置读取返回数据超时时间
            //urlConnection.setReadTimeout(10000);
            if (propertys != null) {
                for (String key : propertys.keySet()) {
                    urlConnection.addRequestProperty(key, propertys.get(key));
                }
            }
            if (method.equalsIgnoreCase("POST") && parameters != null) {
                OutputStream opt = urlConnection.getOutputStream();
                opt.write(encode(param.toString()).getBytes());
                opt.flush();
                opt.close();
            }

            HttpRespons httpResponser = getHttpRespons();
            String ecod = "UTF-8";
            InputStream input = urlConnection.getInputStream();
            byte[] bytay = getByteArr(input);
            //判断是否为文本
            boolean isText = true;
            for (int i = 0; i < bytay.length; i++) {
                if (bytay[i] == 0) {
                    isText = false;
                    break;
                }
            }
            httpResponser.isText = isText;    //判断是否文本格式
            httpResponser.bytay = bytay;    //字节数组
            httpResponser.urlString = url;
            httpResponser.defaultPort = urlConnection.getURL().getDefaultPort();
            httpResponser.file = urlConnection.getURL().getFile();
            httpResponser.host = urlConnection.getURL().getHost();
            httpResponser.path = urlConnection.getURL().getPath();
            httpResponser.port = urlConnection.getURL().getPort();
            httpResponser.protocol = urlConnection.getURL().getProtocol();
            httpResponser.query = urlConnection.getURL().getQuery();
            httpResponser.ref = urlConnection.getURL().getRef();
            httpResponser.userInfo = urlConnection.getURL().getUserInfo();

            //httpResponser.content = content;
            httpResponser.contentEncoding = ecod;
            httpResponser.code = urlConnection.getResponseCode();
            httpResponser.message = urlConnection.getResponseMessage();
            httpResponser.contentType = urlConnection.getContentType();
            httpResponser.method = urlConnection.getRequestMethod();
            httpResponser.connectTimeout = urlConnection.getConnectTimeout();
            httpResponser.readTimeout = urlConnection.getReadTimeout();
            return (T) httpResponser;
        } catch (IOException e) {
            if (urlConnection != null) {
                System.out.println("url: " + urlConnection.getURL());
            }
            throw e;
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
        }
    }
}
